import atexit
from config import app_state
from services import update_persons

def init_scheduler():
    """安全初始化调度器"""
    with app_state.lock:
        if not app_state.initialized:
            # 配置定时任务
            app_state.scheduler.add_job(
                func=update_persons,
                trigger='interval',
                minutes=1,
                max_instances=1,
                coalesce=True,
                misfire_grace_time=300
            )

            # 启动前状态检查
            if not app_state.scheduler.running:
                try:
                    app_state.scheduler.start()
                    print("调度器启动成功")
                except Exception as e:
                    print(f"调度器启动失败: {str(e)}")
                    raise

            # 首次数据加载
            update_persons()
            app_state.initialized = True
            print("应用初始化完成")

def shutdown_scheduler():
    """安全关闭例程"""
    with app_state.lock:
        if app_state.scheduler.running:
            app_state.scheduler.shutdown(wait=False)
            print("调度器已关闭")

atexit.register(shutdown_scheduler)